const md5 = require('js-md5');
const fs = require('fs');

class HTMLIndexMD5Plugin {
  scriptRegExp = /(?=<script.*?>)/;
  outMd5 = {};

  constructor(options) {
    this.options = options;
  }

  apply(compiler) {
    let self = this;
    compiler.plugin('compilation', function (compilation, options) {
      // 编译模板的最后阶段
      compilation.plugin('html-webpack-plugin-after-html-processing', function (pluginArgs) {
        let htmlMd5 = md5(pluginArgs.html);
        self.outMd5[pluginArgs.outputName + '.md5'] = htmlMd5;

        let js = `<script>window.PAGE_MD5 = '${htmlMd5}'</script>`;

        let html = pluginArgs.html.split(self.scriptRegExp);
        let firstScriptIndex = html.findIndex(code => code.startsWith('<script'));
        html.splice(firstScriptIndex, 0, js);
        pluginArgs.html = html.join('');
        return pluginArgs;
      });
    });

    // 编译完成
    compiler.plugin('done', function (pluginArgs) {
      let outputPath = pluginArgs.compilation.compiler.outputPath;
      for (let o in self.outMd5) {
        fs.writeFile(outputPath + '/' + o, self.outMd5[o], () => { });
      }

      return pluginArgs;
    });
  }
}

module.exports = HTMLIndexMD5Plugin;